package com.ruoyi.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.YhMember;
import com.ruoyi.common.core.domain.entity.YhOrder;
import com.ruoyi.common.core.domain.entity.vo.YhOrderVo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.kit.core.enums.OrderStateEnums;
import com.ruoyi.system.domain.YhCommissionRecord;
import com.ruoyi.system.domain.YhMemberLevelRule;
import com.ruoyi.system.mapper.YhOrderMapper;
import com.ruoyi.system.service.IYhCommissionRecordService;
import com.ruoyi.system.service.IYhMemberLevelRuleService;
import com.ruoyi.system.service.IYhMemberService;
import com.ruoyi.system.service.IYhOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 会员购买订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-06-06
 */
@Service
@Slf4j
public class YhOrderServiceImpl extends ServiceImpl<YhOrderMapper, YhOrder> implements IYhOrderService
{

    @Autowired
    private YhOrderMapper yhOrderMapper;

    @Autowired
    private IYhMemberService memberService;
    @Autowired
    private IYhMemberLevelRuleService memberLevelRuleService;
    @Autowired
    private IYhCommissionRecordService commissionRecordService;

    @Transactional
    @Override
    public void payOrder(String sn, String paymentMethod, String receivableNo) {
        // 更新订单状态
        YhOrder yhOrder = this.getOne(new LambdaQueryWrapper<YhOrder>()
                .eq(YhOrder::getSn, sn));
        yhOrder.setCompleteTime(new Date());
        yhOrder.setPaymentTime(new Date());
        yhOrder.setPayOrderNo(receivableNo);
        yhOrder.setOrderStatus(OrderStateEnums.PAID.name());
        yhOrder.setUpdateBy(yhOrder.getCreateBy());
        this.updateById(yhOrder);
        log.info("更新order：{}", yhOrder);
        // 更新用户会员等级
        YhMember byId = memberService.getById(yhOrder.getMemberId());
        byId.setMemberLevel(yhOrder.getMemberLevel());
        byId.setUpdateBy("admin");
        memberService.updateById(byId);
        log.info("更新YhMember：{}", byId);
        // 上级分佣
        String parentId = byId.getParentId();
        if(StringUtils.isNotEmpty(parentId)){
            YhMember parentMember = memberService.getById(parentId);
            if(parentMember == null) return;
            // 获取当前会员等级佣金提成比列
            YhMemberLevelRule yhMemberLevelRule = memberLevelRuleService.getOne(new LambdaQueryWrapper<YhMemberLevelRule>()
                    .eq(YhMemberLevelRule::getMemberLevel, parentMember.getMemberLevel()));
            Double commissionRate = yhMemberLevelRule.getCommissionRate();
            Double flowPrice = yhOrder.getFlowPrice();
            double round = Arith.round(Arith.mul(commissionRate * 0.01, flowPrice), 2);
            // 累计会员佣金
            Double commission = parentMember.getCommission() == null ? 0 : parentMember.getCommission();
            parentMember.setCommission(Arith.add(commission, round));
            parentMember.setUpdateBy("admin");
            memberService.updateById(parentMember);

            // 添加佣金记录
            YhCommissionRecord commissionRecord = new YhCommissionRecord();
            commissionRecord.setMemberId(parentMember.getId());
            commissionRecord.setChildMemberId(byId.getId());
            commissionRecord.setType("POSTER_SHARING");
            commissionRecord.setCommission(round);
            commissionRecord.setMemberLevel(yhOrder.getMemberLevel());
            commissionRecordService.save(commissionRecord);
        }
    }


    @Override
    public YhOrder saveOrder(YhOrder yhOrder) {
        String memberLevelRuleId = yhOrder.getMemberLevelRuleId();
        Long userId = SecurityUtils.getUserId();
        YhMember yhMember = memberService.getById(userId);
        YhMemberLevelRule memberLevelRule = memberLevelRuleService.getById(memberLevelRuleId);
        if(yhMember.getMemberLevel() > memberLevelRule.getMemberLevel()){
            throw new ServiceException("只能购买更高等级的会员！");
        }

        if(memberLevelRule != null || yhMember != null) {
            Integer memberLevel = memberLevelRule.getMemberLevel();
            Double price = memberLevelRule.getPrice();
            yhOrder.setMemberId(userId.toString());
            yhOrder.setMemberName(yhMember.getNickName());
            yhOrder.setMemberLevel(memberLevel);
            yhOrder.setGoodsPrice(price);
            yhOrder.setFlowPrice(price);
            yhOrder.setSn("sn" + DateUtils.dateTimeNow(DateUtils.YYMMDD) + IdUtil.getSnowflake().nextIdStr());
            yhOrder.setOrderStatus(OrderStateEnums.UNPAID.name());
            this.save(yhOrder);
        }else{
            throw new ServiceException("所购买的会员等级不存在！");
        }

        return yhOrder;
    }

    @Override
    public List<YhOrderVo> orderList(YhOrder yhOrder) {
        return yhOrderMapper.orderList(yhOrder.queryWrapper());
    }

}
